import { useState, useEffect, useRef } from "react";
import { Form, Select, message, Input, notification } from "antd";
import { CommonModal } from "@/views/components/CommonModal";
import { makeinventoryScanCode } from "../service";
import IconFont from '@/components/IconFont';

const FillPurchaseModal = ({ visible, query, onChildValueChange, selectedKeys, handleOk, handleCancel }) => {
	const [form] = Form.useForm();
	const [uniqueCodeNum, setUniqueCodeNum] = useState(false);
	const inputEl = useRef(null); //获取的内容的ref

	const [uniCodeList, setUniCodeList] = useState([]);
	const [uniCodeList2, setUniCodeList2] = useState([]);

	useEffect(() => {
		let evenNumbers = selectedKeys.filter(function (item) {
			return item.uniqueCode !== "";
		});
		setUniqueCodeNum(evenNumbers.length);
		if (visible) {
			form.resetFields();
		}
	}, [visible]);
	const commonPressEnter = async e => {
		// const val = e.target.value && e.target.value.replace(/\s/g, "");
		const { data, success } = await makeinventoryScanCode({ code: e });
		if (success) {
			if (data) {
				if (data.outboundDiscard) {
					const { code, discardReason, systemNo } = data;
					notification.warning({
						icon: <IconFont type="iconjingshi" />,
						message: (
							<span className="common-color13">
								商品“{code}”关联销售出库单已作废
								{discardReason == 1 ? <span className="common-color9">（退款商品）</span> : discardReason == 2 ? '（非退款商品）' : ''}
							</span>
						),
						description: `作废原因：订单“${systemNo}”${discardReason == 3 ? '信息变更' : '退款中'}`,
						duration: 5,
					})
				}
				uniCodeList2.push(data);
				const uniqueById = uniCodeList2.filter((item, index, self) => {
					return self.findIndex(t => t.id === item.id) === index;
				});
				form.resetFields();
				setUniCodeList(uniqueById);
				inputEl?.current?.focus();
			}
		}
	};
	const onOk = () => {
		onChildValueChange(uniCodeList);
		onCancel();
	};
	const onCancel = () => {
		handleCancel();
		form.resetFields();
	};

	return (
		<CommonModal title={{ title: "扫码填充" }} visible={true} onOk={onOk} onCancel={onCancel} minHeight="150px">
			<Form form={form} name="mark-unuaual-modal">
				<Form.Item label="商品唯一码" name="timeOutType">
					<Input onPressEnter={e => commonPressEnter(e.target.value)} autoFocus></Input>
				</Form.Item>
				<Form.Item label="本次扫码记录" name="timeOutType">
					<div style={{ color: "rgba(240, 61, 41, 1)" }}>{uniCodeList.length}</div>
				</Form.Item>
				<div style={{ overflow: "auto", width: "100%", background: "rgba(244, 247, 255, 1)", borderRadius: 10 }}>
					{uniCodeList && uniCodeList.map(x => <div>{x.code}</div>)}
				</div>
			</Form>
		</CommonModal>
	);
};

export default FillPurchaseModal;
